<!--组件：按照组织机构统一为用户授权-->
<template>
  <div>
    <a-button @click="openDrawer">按组织机构激活</a-button>

    <a-drawer
      :visible="visible"
      title="按组织机构激活"
      :width="480"
      @cancel="closeDrawer"
      @before-ok="activeUserByDept"
      @ok="activeDept"
    >
      <a-alert title="按组织机构激活" style="margin-bottom: 20px"
        >对选中组织机构下所有人员进行激活</a-alert
      >
      <a-input-search
        v-model="searchTreeKey"
        style="margin-bottom: 5px"
        @input="searchTreeData"
      />
      <!-- <a-tree
        v-model:selected-keys="selectedTreeKeys"
        v-model:expanded-keys="expandedTreeKeys"
        v-model:checked-keys="checkedKeys"
        :checkable="true"
        :check-strictly="true"
        :max="1"
        block-node
        :field-names="{
          key: 'code',
          title: 'name',
          children: 'children',
        }"
        :data="treeDataFilter"
        @select="onSelectTreeNode"
        @check="onCheckTreeNode"
      > -->
      <a-tree
        v-model:selected-keys="selectedTreeKeys"
        v-model:expanded-keys="expandedTreeKeys"
        block-node
        :field-names="{
          key: 'code',
          title: 'name',
          children: 'children',
        }"
        :data="treeDataFilter"
        @select="onSelectTreeNode"
      >
        <template #icon>
          <icon-home />
        </template>
        <template #title="nodeData">
          <span v-if="nodeData?.name.indexOf(searchTreeKey) > -1">
            {{
              nodeData?.name.substr(0, nodeData?.name.indexOf(searchTreeKey))
            }}
            <span style="color: #f50">{{ searchTreeKey }}</span>
            {{
              nodeData?.name.substr(
                nodeData?.name.indexOf(searchTreeKey) + searchTreeKey?.length
              )
            }}
          </span>
          <span v-else>{{ nodeData?.name }}</span>
        </template>
      </a-tree>
    </a-drawer>
  </div>
</template>

<script setup lang="ts" name="RoleDeptDrawer">
  import { ref, watch, defineEmits } from 'vue';
  import { Notification, Message } from '@arco-design/web-vue';
  // import { queryRoleRecordList } from '@/api/system/role';
  // import { RoleRecord } from '@/api/system/model/roleModel';
  import { queryDeptRecordTreeList } from '@/api/system/dept';
  import { queryUserRecordList, activeUserBatch } from '@/api/system/user';
  import { UserParams, UserRecord } from '@/api/system/model/userModel';

  const treeData = ref<any[]>([]); // 树
  const treeDataFilter = ref<any[]>([]); // 用于搜索的过滤树
  const searchTreeKey = ref<string>(); // 树顶上的搜索框关键字
  const filterKeySet = new Set(); // 定义一个集合，用于记录过滤keys
  const dataList = ref<any[]>([]); // treeData的所有key:title:id
  const parentKeys = ref<string[]>([]); // 用于存储点击的树节点的所有父节点的key
  const expandedTreeKeys = ref<string[]>([]); // 已展开的树节点keys
  const selectedTreeKeys = ref<string[]>([]); // 已选中的树节点keys
  const checkedKeys = ref<string[]>([]);
  // const searchRef = ref<any>();
  const treeDataLoading = ref<boolean>(false); // 指示树形组件是否正在加载中
  const currentSearchParams = ref<UserRecord>({}); // 记录当前的搜索条件
  const userlist = ref<any>([]);
  const emit = defineEmits(['refresh']);

  watch(
    () => parentKeys,
    (val) => {
      if (val) {
        val.value.forEach((element: any) => {
          filterKeySet.add(element);
        });
        // 进行过滤操作
        treeDataFilter.value = treeData.value.filter((item) =>
          filterKeySet.has(item.code)
        );
        expandedTreeKeys.value = [...filterKeySet] as string[];
      }
    },
    { deep: true, immediate: true }
  );
  // defineProps({
  //   deptTree: { type: Array as PropType<TreeNodeData[]>, default: () => [] },
  // });
  /**
   * @description 获取部门的树形结构信息
   */
  const getTreeData = async () => {
    treeDataLoading.value = true;
    treeData.value = [];
    treeDataFilter.value = [];
    try {
      const { data } = await queryDeptRecordTreeList({});
      treeData.value = data;
      treeDataFilter.value = data;
      dataList.value = [];
      generateList(treeData.value);
    } catch (error) {
      Notification.error({
        content: `出现异常！${error}`,
        closable: true,
        duration: 20000,
      });
    } finally {
      treeDataLoading.value = false;
    }
  };
  /**
   * @description 构建treeData的所有 { key: title: id } 数组
   * @param data 树节点数据
   */
  const generateList = (data: any) => {
    // 创建dataList 递归调用
    data.forEach((item: any) => {
      const node = item;
      const key = node.code;
      dataList.value.push({ key, title: node.name, id: node.id });
      if (node.children) {
        generateList(node.children);
      }
    });
  };
  const visible = ref<boolean>(false); // 抽屉是否可见
  // 打开激活抽屉
  const openDrawer = () => {
    // getRoleList();
    getTreeData();
    visible.value = true;
  };
  // 关闭激活抽屉
  const closeDrawer = () => {
    searchTreeKey.value = '';
    visible.value = false;
    // formRef.value.resetFields();
  };
  /**
   * 点击树节点触发
   * @param newSelectedKeys
   * @param event
   */
  const onSelectTreeNode = async (newSelectedKeys: any, event: any) => {
    // console.log('selectedTreeKeys', selectedTreeKeys);
    // selectedTreeKeys.value = selectedTreeKeys.value.filter(
    //   (t) => t !== newSelectedKeys
    // );
    selectedTreeKeys.value = newSelectedKeys;
    // console.log('selectedTreeKeys.value', selectedTreeKeys.value);
    // console.log('newSelectedKeys', newSelectedKeys);
    checkedKeys.value = newSelectedKeys;
    if (event.node.children) {
      let flag = false;
      expandedTreeKeys.value.forEach((item: string) => {
        if (item === newSelectedKeys[0]) {
          flag = true;
        }
      });
      if (!flag) {
        expandedTreeKeys.value.push(newSelectedKeys[0]);
      }
    }
    // searchRef.value.setFormValues({ deptCode: newSelectedKeys[0] }); // 给搜索组件设置对应的部门编码
    currentSearchParams.value = { deptCode: newSelectedKeys[0] };
    getUserDetailInfo();
  };
  // const onCheckTreeNode = async (newCheckedKeys: any, event: any) => {
  //   // console.log('newCheckedKeys', newCheckedKeys);
  //   checkedKeys.value = newCheckedKeys;
  //   console.log('checkedKeys.value', checkedKeys.value);
  //   selectedTreeKeys.value = newCheckedKeys;
  //   if (event.node.children) {
  //     let flag = false;
  //     expandedTreeKeys.value.forEach((item: string) => {
  //       if (item === newCheckedKeys[0]) {
  //         flag = true;
  //       }
  //     });
  //     if (!flag) {
  //       expandedTreeKeys.value.push(newCheckedKeys[0]);
  //     }
  //   }
  //   // searchRef.value.setFormValues({ deptCode: newCheckedKeys[0] }); // 给搜索组件设置对应的部门编码
  //   currentSearchParams.value = { deptCode: newCheckedKeys[0] };
  //   console.log('currentSearchParams.value', currentSearchParams.value);
  //   getUserDetailInfo();
  // };
  /**
   * @description 根据子节点的key获取父节点的key
   * @param key key
   * @param tree 树节点
   */
  const getParentKey = (key: string, tree: any) => {
    let parentKey;
    tree.forEach((elem: any) => {
      const node = elem;
      if (node.children) {
        if (node.children.some((item: any) => item.code === key)) {
          parentKey = node.code;
        } else if (getParentKey(key, node.children)) {
          parentKey = getParentKey(key, node.children);
        }
      }
    });
    return parentKey;
  };
  /**
   * @description 获取完整地父节点的key数组 递归调用
   * @param key
   */
  const getWholeParentKeys = (key: string) => {
    const temp = getParentKey(key, treeData.value);
    if (temp !== undefined) {
      parentKeys.value.push(temp);
      getWholeParentKeys(temp);
    }
  };
  /**
   * @description 树形结构上面的搜索框发生改变会触发此函数
   * @param value
   */
  const searchTreeData = (val: any) => {
    const value = val.replaceAll(' ', '');
    filterKeySet.clear();
    // 进行搜索操作
    const expandedKeysTemp = [] as any[];
    dataList.value.forEach((item) => {
      if (item.title && item.title.indexOf(value) > -1) {
        expandedKeysTemp.push(item.key);
      }
    });
    parentKeys.value = [];
    // 必须要有下面这个forEach，否则只能查到2层数据，因为超过了2层后匹配不到更上层的父id，进而导致搜索不出结果
    expandedKeysTemp.forEach((item: string) => {
      filterKeySet.add(item);
      getWholeParentKeys(item); // 把原始的expandedKeysTemp中的每个key对应的完整父key都放进parentKeys保存
    });
    expandedTreeKeys.value =
      value.trim().length === 0 ? [] : ([...filterKeySet] as string[]);
    searchTreeKey.value = value;
    // 进行过滤操作
    treeDataFilter.value = treeData.value.filter((item) =>
      filterKeySet.has(item.code)
    );
  };
  // 根据树节点获取用户信息
  const getUserDetailInfo = async () => {
    const params: UserParams = {
      page: 1,
      limit: 10000,
      ...currentSearchParams.value, // 按条件搜索，如果有的话
    };
    const { data } = await queryUserRecordList(params);
    console.log('data', data);
    // userlist.value = data.list.filter((e) => e.activated !== 'true');
    data.list.forEach((e) => {
      console.log('e.activated', e.activated);
      if (!e.activated) {
        console.log('e.id', e.id);
        userlist.value.push(e.id);
      }
    });
  };
  // 激活用户
  const activeUserByDept = async () => {
    console.log('userlist.value', userlist.value);
    await activeUserBatch(userlist.value);
    Message.success('激活成功');
  };
  const activeDept = () => {
    emit('refresh');
    visible.value = false;
  };
</script>
